
package org.test;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

/*This is the main entry point of the entire application.
 * An existing enters its login information and then can use 
 * various features like buy and sell.
 * Once logged in its sessions starts and can only be ended when he or she
 * selects the logout button on the sell tab of the application.
 * */
public class ExistingUserLogInActivity extends Activity {

	private String[] Courses = new String[20];
	private int counter = 0;
	private int flag = 0;
	private EditText E_ID, E_Password;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.existinguserloginlayout);

		E_Password = (EditText) findViewById(R.id.password);
		E_ID = (EditText) findViewById(R.id.id);

		E_ID.getText().toString();
		E_Password.getText().toString();
	}
	
	//When the user presses "Sign in" the user name and password is cross checked in the 
	//remote database and if found incorrect gives the user error message or else enters the 
	//user successfully
	public void onClick(View view) {
		String result = "";

		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();

		//HTTP request sent to remote database to check whether the login information is
		//correct or not
		
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(
				"http://hci.cs.sfsu.edu/~fall2010.03/Includes/TestIDPassword.php");
		try {
			httppost.setEntity(new UrlEncodedFormEntity(postParameters));

			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			InputStream is = entity.getContent();

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();

			result = sb.toString();
		} catch (Exception e) {
			Log.e("log_tag", "Error converting result " + e.toString());
		}

		try {
			JSONArray jArray = new JSONArray(result);

			for (int i = 0; i < jArray.length(); i++) {
				JSONObject json_data = jArray.getJSONObject(i);
				Log.i("log_tag", " Name: " + json_data.getString("Name")
						+ ", Password: " + json_data.getString("Password")
						+ ", ID: " + json_data.getString("ID"));

				Courses[counter] = json_data.getString("Password");
				counter++;

				System.out.println("Passord" + E_Password.getText().toString());

				if (json_data.getString("Password").equals(
						E_Password.getText().toString())
						&& json_data.getString("ID").equals(
								E_ID.getText().toString())
						&& !E_ID.getText().toString().equals("")) {
					flag = 1;
					System.out.println("Pass !!!!");

					//User is valid and hence allowed to login successfully
					
					Toast.makeText(this,
							"Welcome " + json_data.getString("Name"),
							Toast.LENGTH_LONG).show();

					Intent i1 = new Intent(this, UserLogedInPageActivity.class);
					i1.putExtra("ID", json_data.getString("ID"));
					startActivity(i1);
				}
			}
			if (flag != 1) {
				System.out.println("Fail !!!!");
				
				
				//User is not valid hence please try again
				Toast.makeText(this, "Incorrect Student ID or Password",
						Toast.LENGTH_LONG).show();
				Intent i1 = new Intent(this, NewOrExisitingUserActivity.class);

				startActivity(i1);

			}
		} catch (JSONException e) {
			System.out.println("NO RECORDS FOUND");
		}

	}

}
